package com.cbarmstrong.FinanceWeb;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cbarmstrong.Finance.Data;

/**
 * Servlet implementation class JsonStockList
 */
@WebServlet("/JsonStockList")
public class JsonStockList extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public JsonStockList() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String ls=System.getProperty("line.separator");
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		String responseText="{ 'identifier': 'id',"+ls+"  'label':'name',"+ls+"  'items': ["+ls;
		try {
			Connection c=Data.initConnection();
			Statement s=c.createStatement();
			ResultSet r=s.executeQuery("SELECT name, id FROM stock");
			while(r.next()){
				responseText+="		{ 'name': '"+r.getString(1)+"', 'id':'"+r.getString(2)+"' }";
				if(!r.isLast()){ responseText+=","+ls; }
			}
			responseText+=ls+"	]"+ls+"}";
			out.print(responseText);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.flush();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
